package com.jiangnan.ui.activity

import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityRechargeBinding
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.util.showConfirmationDialog
import com.jiangnan.util.showQrPaymentDialog
import com.jiangnan.viewmodel.RechargeViewModel
import com.jiangnan.viewmodel.UserViewModel

import java.math.BigDecimal

class RechargeActivity : BaseActivity() {
    private lateinit var binding: ActivityRechargeBinding
    private lateinit var vm: RechargeViewModel
    private lateinit var userViewModel: UserViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRechargeBinding.inflate(layoutInflater)
        setContentView(binding.root)

        vm = ViewModelProvider(this)[RechargeViewModel::class.java]
        userViewModel = ViewModelProvider(this)[UserViewModel::class.java]

        userViewModel.loadUser(SharedPrefUtil.getLoginInfo(this)!!.id.toLong())
        userViewModel.user.observe(this) { user ->
            binding.tvBalance.text = "当前余额：${"%.2f".format(user?.accountMoney)}"
        }

        // 观察
        vm.balance.observe(this) { bal ->
            binding.tvBalance.text = "当前余额：${"%.2f".format(bal)}"
        }
        vm.error.observe(this) { msg ->
            ToastUtil.showShort(this, msg)
        }
        vm.toastMessage.observe(this) { msg ->
            ToastUtil.showShort(this, msg)
        }

        // 点击充值
        binding.btnRecharge.setOnClickListener {
            val userId = SharedPrefUtil.getLoginInfo(this)!!.id.toLong()
            val amtStr = binding.etAmount.text.toString()
            if (userId < 0 || amtStr.isBlank()) return@setOnClickListener
            val amt = BigDecimal(amtStr)

            showQrPaymentDialog(
                context = this,
                qrDrawableRes = R.drawable.wx_pay,
                message = "请扫描上方二维码完成充值 ¥${"%.2f".format(amt)}"
            ) {
                // 点击“确定”后真正发起充值
                vm.recharge(userId, amt)
            }
        }
    }
}